<template>
  <component class="ueditor-plus" is="script" v-if="loaded" :id="id" type="text/plain" style="height:300px;"></component>
  <ElInput key="input" v-else :="$attrs" />
</template>

<script lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import { ElInput } from 'element-plus'

const LOADED_URLS = new Set()

let _uuid = 0
function getId() {
  return `ueditor-plus-${++_uuid}`
}

function loeadJs(url) {
  if (LOADED_URLS.has(url)) return Promise.resolve()
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = url
    document.head.appendChild(script)
    script.onload = () => {
      LOADED_URLS.add(url)
      resolve({})
    }

    script.onerror = e => {
      reject(e)
    }
  })
}

function loead() {
  const configUrl = new URL('/ueditor-plus/ueditor.config.js', import.meta.url).href
  const allUrl = new URL('/ueditor-plus/ueditor.all.js', import.meta.url).href
  return Promise.all([loeadJs(configUrl), loeadJs(allUrl)])
}
export default {
  components: {
    ElInput
  },
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:model-value'],
  setup(props, { emit }) {
    const loaded = ref(false)
    const id = ref(getId())

    onMounted(async () => {
      await loead()
      loaded.value = true
      await nextTick()
      const ue = UE.getEditor(id.value, {
        UEDITOR_HOME_URL: `${import.meta.env.BASE_URL}/ueditor-plus/`,
        lang: 'zh-cn',
        initialFrameWidth: '100%',
        // serverUrl: import.meta.env.VITE_APP_API_BASE_URL + '/sys/file/upload',
        imageActionName: import.meta.env.VITE_APP_API_BASE_URL + '/sys/file/upload',
        imageFieldName: 'file',
        imageUrlPrefix: '',
        imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"],
        imageConfig: {
          disableOnline: true
        }
      })

      console.log(import.meta.env.VITE_APP_API_BASE_URL + '/sys/file/upload')
      
      ue.ready(() => {
        ue.setContent(props.modelValue)
      });

      ue.addListener('contentChange', () => {
        emit('update:model-value', ue.getContent())
      })
    })

    return {
      loaded,
      id
    }
  }
}
</script>

<style>
.ueditor-plus {
  width: 100%;
  box-sizing: border-box;
}
</style>
